package com.jz.community.moduleshopping.shopCart.ui;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.constant.ConstantErrorCode;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.NumberArithmeticUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTextTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToCartRefreshEvent;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.LoginCallback;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.shopCart.adapter.InvalidCartItemAdapter;
import com.jz.community.moduleshopping.shopCart.adapter.ShopCartAdapter;
import com.jz.community.moduleshopping.shopCart.bean.CartGoodInfo;
import com.jz.community.moduleshopping.shopCart.bean.CartPostageInfo;
import com.jz.community.moduleshopping.shopCart.bean.CartShopInfo;
import com.jz.community.moduleshopping.shopCart.bean.NewCartListInfo;
import com.jz.community.moduleshopping.shopCart.presenter.ShopCartPresenter;
import com.jz.community.moduleshopping.shopCart.task.GetShopCartListTask;
import com.jz.community.moduleshopping.shopCart.task.GetShopCartPostageTask;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.kingja.loadsir.core.Transport;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Optional;
import io.reactivex.Observable;

/**
 * Created by Tony.Fan on 2018/5/18 14:01
 * <p>
 * 购物车
 */
@Route(path = RouterIntentConstant.MODULE_SHOPPING_CART)
public class ShoppingCartFragment extends BaseMvpFragment implements OnRefreshListener, ShoppingCartView {
    @Nullable
    @BindView(R2.id.cart_delete_goods)
    ImageView cartDeleteGoods;
    @Nullable
    @BindView(R2.id.cart_home_toolbar)
    Toolbar cartHomeToolbar;
    @Nullable
    @BindView(R2.id.cart_title)
    TextView cartTitle;
    @Nullable
    @BindView(R2.id.cart_recyclerview)
    RecyclerView cartRecyclerview;
    @Nullable
    @BindView(R2.id.cart_refresh)
    SmartRefreshLayout cartRefresh;
    @Nullable
    @BindView(R2.id.shop_cart_check)
    CheckBox shopCartCheck;
    @Nullable
    @BindView(R2.id.cart_self_choose_ll)
    LinearLayout cartSelfChooseLl;
    @Nullable
    @BindView(R2.id.cart_self_price)
    TextView cartSelfPrice;
    @Nullable
    @BindView(R2.id.cart_self_pay_num)
    TextView cartSelfPayNum;
    @Nullable
    @BindView(R2.id.cart_self_pay_ll)
    LinearLayout cartSelfPayLl;
    @Nullable
    @BindView(R2.id.cart_self_bot_ll)
    LinearLayout cartSelfBotLl;
    @Nullable
    @BindView(R2.id.shop_cart_layout)
    RelativeLayout shopCartLayout;
    @Nullable
    @BindView(R2.id.cart_tips_tv)
    TextView cartTipsTv;
    @Nullable
    @BindView(R2.id.cart_tips_btn)
    TextView cartTipsBtn;
    @Nullable
    @BindView(R2.id.cart_tips_layout)
    LinearLayout cartTipsLayout;
    private ShopCartPresenter shopCartPresenter;
    private int totalNum = 0;
    private ShopCartAdapter shopCartAdapter;
    protected LoadService loadService;
    private boolean isOneChoose;
    private Observable<ToLoginEvent> toLoginRxBusObser;
    private Observable<ToCartRefreshEvent> toCartRefreshRxBusObser;
    private RecyclerView cartInValidListRv;
    private InvalidCartItemAdapter invalidCartItemAdapter;
    private View footView;
    private NewCartListInfo newCartListInfo;
    private CartPostageInfo cartPostageInfo;
    private double postagePrice;

    @Override
    protected void initView() {
        loadService = LoadSir.getDefault().register(shopCartLayout);

        loadService.setCallBack(EmptyCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                TextView mTvEmpty = view.findViewById(R.id.empty_tv);
                mTvEmpty.setText("还是空的...");
                SHelper.gone(cartTipsLayout);
            }
        });

        loadService.setCallBack(LoginCallback.class, new Transport() {
            @Override
            public void order(Context context, View view) {
                TextView mTvLogin = view.findViewById(R.id.empty_login_btn);
                mTvLogin.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN);
                    }
                });
            }
        });
        foodView();
        registerLoginByRxBus();
        registerCartRefreshByRxBus();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shopping_fragment_cart_home;
    }

    @Override
    protected void initVisible() {
        super.initVisible();
        setImmersionBar(cartHomeToolbar);
    }

    /**
     * 登录处理
     */
    @SuppressLint("CheckResult")
    private void registerLoginByRxBus() {
        toLoginRxBusObser = RxBus.getInstance().register(ToLoginEvent.toLoginRxBusTag, ToLoginEvent.class);
        toLoginRxBusObser.subscribe(toLoginEvent -> {
            handleLoginState(toLoginEvent);
        }, throwable -> {
        });
    }

    /**
     * 刷新购物车
     */
    @SuppressLint("CheckResult")
    private void registerCartRefreshByRxBus() {
        toCartRefreshRxBusObser = RxBus.getInstance().register(ToCartRefreshEvent.toCartRefreshRxBusTag, ToCartRefreshEvent.class);
        toCartRefreshRxBusObser.subscribe(toCartRefreshEvent -> ShoppingCartFragment.this.handleCartRefreshState(toCartRefreshEvent), throwable -> {
        });
    }

    public void refreshCart() {
        if (isSupportVisible()) {
            loadCartListTask(true);
        }
    }

    /**
     * 登录状态
     *
     * @param toLoginEvent
     */
    private void handleLoginState(ToLoginEvent toLoginEvent) {
        if (toLoginEvent.isToPwdLogin() || toLoginEvent.isToWeChatLogin()) {
            loadCartListTask(true);
        } else {
            loadService.showCallback(LoginCallback.class);
        }
    }

    /**
     * 刷新购物车
     *
     * @param toCartRefreshEvent
     */
    private void handleCartRefreshState(ToCartRefreshEvent toCartRefreshEvent) {
        if (toCartRefreshEvent.isShopCartRefresh()) {
            loadCartListTask(true);
            shopCartPresenter.changeShopSelect(false);
        } else {
            loadService.showCallback(EmptyCallback.class);
        }
    }

    @Override
    protected void initDatas() {
        showCartNumAndPrice(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble("0")), totalNum + "");
        shopCartPresenter = new ShopCartPresenter(this);
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        loadCartListTask(true);
    }

    /**
     * 获取购物列表
     */
    private void loadCartListTask(boolean isRefresh) {
        if (BaseUserUtils.getIsLogin(getActivity())) {
            new GetShopCartListTask(getActivity(), o -> {
                newCartListInfo = (NewCartListInfo) o;
                if (!Preconditions.isNullOrEmpty(newCartListInfo) && !Preconditions.isNullOrEmpty(newCartListInfo.getValidGoods())) {
                    loadService.showSuccess();
                    setData(newCartListInfo, isRefresh);
                    getShopPostageData(isRefresh);
                    shopCartCheck.setEnabled(true);
                } else {
                    showCartNumTitle(0);
                    shopCartCheck.setEnabled(false);
                    SHelper.gone(cartSelfBotLl, cartDeleteGoods, cartTipsLayout);
                    loadService.showCallback(EmptyCallback.class);
                }
            }, isRefresh).execute();
        } else {
            loadService.showCallback(LoginCallback.class);
            showCartNumTitle(0);
            SHelper.gone(cartTipsLayout);
        }
    }

    /**
     * 获取店铺邮费
     */
    private void getShopPostageData(boolean isRefresh) {
        new GetShopCartPostageTask(getActivity(), new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                cartPostageInfo = (CartPostageInfo) o;
                if (!Preconditions.isNullOrEmpty(cartPostageInfo)) {
                    shopCartPresenter.addShopPostageInfo(cartPostageInfo);
                    showCartShopPostageTitle(0, false);
                }
            }
        }, false).execute();
    }

    private void setData(NewCartListInfo newCartListInfo, boolean isRefresh) {
        SHelper.vis(cartSelfBotLl, cartDeleteGoods);
        showCartNumTitle(newCartListInfo.getTotal());
        showCartShopPostageTitle(0, false);
        loadShopCart(newCartListInfo, isRefresh);
    }

    /**
     * 加载购物列表
     *
     * @param newCartListInfo
     */
    private void loadShopCart(NewCartListInfo newCartListInfo, boolean isRefresh) {

        if (isRefresh) {
            shopCartPresenter.addShopNewCartListInfo(newCartListInfo);
        } else {
            shopCartPresenter.addShopNewRefreshCartListInfo(newCartListInfo);
        }
        cartRefresh.finishRefresh();
        handleBindCartAdapter(newCartListInfo, isRefresh);
        if (!Preconditions.isNullOrEmpty(newCartListInfo.getInvalidGoods())) {
            SHelper.vis(footView);
            handleBindCartInValidItemAdapter(newCartListInfo.getInvalidGoods());
        } else {
            SHelper.gone(footView);
        }
    }

    /**
     * 绑定购物有效列表
     *
     * @param newCartListInfo
     */
    private void handleBindCartAdapter(NewCartListInfo newCartListInfo, boolean isRefresh) {
        if (shopCartAdapter == null) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            cartRecyclerview.setLayoutManager(layoutManager);
            cartRefresh.setOnRefreshListener(this);
            shopCartAdapter = new ShopCartAdapter(newCartListInfo.getValidGoods(), shopCartPresenter);
            shopCartAdapter.setFooterView(footView);
            cartRecyclerview.setAdapter(shopCartAdapter);
        } else {
            if (isRefresh) {
                shopCartAdapter.replaceData(newCartListInfo.getValidGoods());
            } else {
                shopCartAdapter.replaceData(shopCartPresenter.getRefreshCartListInfo());
            }
        }
        shopCartAdapter.setCheckShopItemListener(new ShopCartAdapter.CheckShopItemListener() {
            @Override
            public void isCheckShopItem(List<CartShopInfo> cartShopInfoList, int position) {
                shopCartAdapter.replaceData(cartShopInfoList);
            }
        });
    }

    private void foodView() {
        footView = LayoutInflater.from(getActivity()).inflate(R.layout.module_shopping_item_cart_invalid_shop_layout, (ViewGroup) cartRecyclerview.getParent(), false);
        cartInValidListRv = footView.findViewById(R.id.cart_invalid_list_rv);
    }

    /**
     * 绑定购物车失效列表
     *
     * @param invalidGoods
     */
    private void handleBindCartInValidItemAdapter(List<CartGoodInfo> invalidGoods) {
        if (invalidCartItemAdapter == null) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            cartInValidListRv.setLayoutManager(layoutManager);
            invalidCartItemAdapter = new InvalidCartItemAdapter(invalidGoods);
            cartInValidListRv.setAdapter(invalidCartItemAdapter);
            invalidCartItemAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                    showDeleteDialog(false, ConverterUtils.toInt(invalidCartItemAdapter.getData().get(position).getId()));
                    return false;
                }
            });
        } else {
            invalidCartItemAdapter.setNewData(invalidGoods);
        }
    }

    /**
     * 购物数量显示
     *
     * @param totalNum
     */
    private void showCartNumTitle(int totalNum) {
        if (!Preconditions.isNullOrEmpty(totalNum)) {
            cartTitle.setText("购物车" + "(" + totalNum + ")");
        } else {
            cartTitle.setText("购物车");
        }
    }

    @Optional
    @OnClick(R2.id.cart_delete_goods)
    public void onDeleteGoods() {
        if (isOneChoose) {
            showDeleteDialog(true, 0);
        } else {
            WpToast.l(getActivity(), "请先选择要删除的商品");
        }
    }

    @Optional
    @OnClick(R2.id.cart_self_pay_ll)
    public void onGoodsBalance() {
        if (isOneChoose) {
            shopCartPresenter.changeBalanceSelectedGoods();
        } else {
            WpToast.l(getActivity(), "您还未选择任何商品");
        }
    }

    @Optional
    @OnClick(R2.id.cart_tips_btn)
    public void cartTipsBtn() {
        Intent intent = new Intent(getActivity(), PieceTogetherGoodsActivity.class);
        intent.putExtra("shopId", cartPostageInfo.getShopId());
        intent.putExtra("salePrice", ConverterUtils.toString(postagePrice));
        startActivity(intent);
    }

    @Optional
    @OnClick(R2.id.shop_cart_check)
    void onChangeGoodsCheckBox() {
        changeGoodsEditAllSelectStatus();
    }

    /**
     * 全选 购物数据刷新
     */
    private void changeGoodsEditAllSelectStatus() {
        boolean isChecked = shopCartCheck.isChecked();
        boolean changedCheck = !isChecked;
        shopCartCheck.setChecked(changedCheck);
        shopCartPresenter.changeShopSelect(isChecked);
        shopCartAdapter.notifyDataSetChanged();
    }

    /**
     * 删除商品
     */
    private void showDeleteDialog(boolean isValid, int cartId) {
        new MaterialDialog.Builder(getActivity()).title("提示").content("是否删除所选商品？").positiveText("删除").negativeText("取消")
                .negativeColor(ContextCompat.getColor(getActivity(), R.color.negative_color))
                .positiveColor(ContextCompat.getColor(getActivity(), R.color.positive_color))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (isValid) {
                            shopCartPresenter.deleteCartGoodsInfo();
                        } else {
                            long ids[] = {cartId};
                            shopCartPresenter.deleteCartInvalidGoodsInfo(ids);
                        }
                    }
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    /**
     * 支付金额、购买数量
     *
     * @param totalAmount
     * @param totalNum
     */
    private void showCartNumAndPrice(String totalAmount, String totalNum) {
        if (isOneChoose) {
            cartSelfPrice.setText("¥" + CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(totalAmount)));
        } else {
            cartSelfPrice.setText("¥" + CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble("0")));
        }
        cartSelfPayNum.setText("结算(" + totalNum + ")");
    }

    /**
     * 满减优惠活动金额
     *
     * @param totalAmount
     */
    private void showCartShopPostageTitle(double totalAmount, boolean isSelected) {
        if (!Preconditions.isNullOrEmpty(cartPostageInfo) && !Preconditions.isNullOrEmpty(cartPostageInfo.getCityName())) {
            if (isSelected) {
                calculateTotalSelectedPostage(totalAmount);
            } else {
                cartTipsTv.setText(getString(R.string.cart_full_postage, CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(cartPostageInfo.getPostagePrice())) + "包邮(" + cartPostageInfo.getCityName() + "除外)"));
            }
            SHelper.vis(cartTipsLayout);
        } else {
            SHelper.gone(cartTipsLayout);
        }
    }

    /**
     * 计算包邮活动
     *
     * @param totalAmount
     */
    private void calculateTotalSelectedPostage(double totalAmount) {
        if (totalAmount >= ConverterUtils.toDouble(cartPostageInfo.getPostagePrice())) {
            cartTipsTv.setText(getString(R.string.cart_already_postage));
            SHelper.gone(cartTipsBtn);
        } else {
            postagePrice = NumberArithmeticUtils.sub(ConverterUtils.toDouble(cartPostageInfo.getPostagePrice()), totalAmount);
            cartTipsTv.setText(getString(R.string.cart_price_postage, CharacterUtils.roundByGoodPrice(postagePrice) + ""));
            SHelper.vis(cartTipsBtn);
            RxTextTool.getBuilder("").append("去凑单").setUnderline()
                    .append(" >")
                    .into(cartTipsBtn);
        }
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        loadCartListTask(false);
    }

    @Override
    public Context getContext() {
        return getActivity();
    }

    @Override
    public void showShoppingCartBuyInfo(double totalAmount, int totalNum, boolean isSelectAll,
                                        boolean isOneChooseBuy, double postagePrice) {
        isOneChoose = isOneChooseBuy;
        showCartNumAndPrice(totalAmount + "", totalNum + "");
        showCartShopPostageTitle(totalAmount, isOneChoose);
        shopCartCheck.setChecked(isSelectAll ? true : false);
    }

    @Override
    public void showShoppingCartBuyNum(int totalShopNum) {
        showCartNumTitle(totalShopNum);
    }

    @Override
    public void showDeleteShopingInfo(BaseResponseInfo baseResponseInfo) {
        if (baseResponseInfo.getCode() == ConstantErrorCode.SUCC_CODE) {
            WpToast.l(getActivity(), "删除成功");
            shopCartPresenter.changeShopSelect(false);
            loadCartListTask(true);
        } else {
            WpToast.l(getActivity(), "删除失败");
        }
    }

    private void unregisterLoginByRxBus() {
        RxBus.getInstance().unregister(ToLoginEvent.toLoginRxBusTag, toLoginRxBusObser);
        RxBus.getInstance().unregister(ToCartRefreshEvent.toCartRefreshRxBusTag, toCartRefreshRxBusObser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterLoginByRxBus();
    }
}
